const express = require('express')
// 路由对象
const userRouter = express.Router()

// 用户数组
const userList = [{id:1, username: 'admin', password: 123 }]

/** 
 * 3. 创建注册路由
 * http://ip:port/reigster
 *     get   url?username=admin&password=123
 *     post  参数在请求体中body
 **/ 
userRouter.post('/register', (req, res) => {
	// 1. 接收参数
	const username = req.body.username
	const password = req.body.password
	console.log('username :',username, ' password:',password);
	

	// 2.注册业务
	const user = { username, password }
	userList.push(user) // 添加到用户数组

    // 3. 响应数据
	res.send({
		code: 1,
		message: '注册成功',
	})
})
/**
 * 登录
 */
userRouter.get('/login', (req, res) => {
	// 1. 接收请求
	const username = req.query.username
	const password = req.query.password
	// 2. 处理业务逻辑
	const user = userList.find(item => item.username == username && item.password == password)
	if (user) {
		// 3. 响应数据
		res.send({
			code: 1,
			message: '登录成功',
		})
	} else {
		// 3. 响应数据
		res.send({
			code: -1,
			message: '用户名或密码出错!',
		})
	}
})

/**
 * 修改用户名为admin的密码123456
 *    path: /user/1
 *      /user/:id 定义动态参数id
 *      /user/1   实参
 *       req.params.id  
 */
userRouter.put('/user/:id',(req,res)=>{
	const id = req.params.id // 动态获取参数
	const username = req.body.username
	const newPassword = req.body.password 

	userList.forEach(item=>{
		if(item.id == id){
			item.username = username
			item.password = newPassword
		}
	})

	res.send({
		code:1,
		message:'修改用户密码成功!'
	})
})

/**
 * 删除用户
 * 根据用户名删除用户名为admin
 */
userRouter.delete('/user',(req,res)=>{
	const username = req.body.username

	const index = userList.findIndex(item=>item.username == username)
	userList.splice(index,1)

	res.send({
		code:1,
		message:'删除用户成功!'
	})
})

module.exports = { userRouter }
